package com.example.flutter_app;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;



import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;

import utils.BitmapUtil;
import utils.ShareImage;
public class BitmapActivity extends Activity {

    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:

                    createBarcode(System.currentTimeMillis()+"");
                    result= BitmapUtil.combineBitmap(bg,bitmap);

                    //  drawTextToBitmap(MainActivity.this,result,"text","text");
                    result1=AddTimeWatermark(result);
                    imageView.setImageBitmap(result1);
                    Toast.makeText(getApplicationContext(),Environment.getExternalStorageDirectory()+ File.separator+System.currentTimeMillis()+".jpg",Toast.LENGTH_LONG).show();
//                          path=Environment.getExternalStorageDirectory()+ File.separator+System.currentTimeMillis()+".jpg";
//                            BitmapUtil.saveBitmapToSDCard(result1, path);

                    //   ShareImage.shareImagesToWeiXin(MainActivity.this,path);
                    btn.setEnabled(true);
                    break;
            }
        }
    };
    ImageView imageView;
    Button btn;
    Bitmap bg;
    Bitmap result;
    Bitmap result1;
    String path;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView=(ImageView)findViewById(R.id.img);
        btn=(Button)findViewById(R.id.btn);
        btn.setEnabled(false);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShareImage.shareImageToWechat(result1,"",BitmapActivity.this);
            }
        });
        new Thread(new Runnable() {
            @Override
            public void run() {
                getBitmap("http://pic9.nipic.com/20100923/2531170_140325352643_2.jpg");
            }
        }).start();

    }


    Bitmap bitmap;

    public Bitmap createBarcode(String str) {
        bitmap = null;
        BitMatrix result = null;
        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        try {
            result = multiFormatWriter.encode(str, BarcodeFormat.QR_CODE, 260, 260);

            int w = result.getWidth();
            int h = result.getHeight();
            int[] pixels = new int[w * h];
            for (int y = 0; y < h; y++) {
                int offset = y * w;
                for (int x = 0; x < w; x++) {
                    pixels[offset + x] = result.get(x, y) ? Color.BLACK : Color.WHITE;
                }
            }
            bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, w, 0, 0, w, h);

        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    public  Bitmap getBitmap(String url) {
        Bitmap bm = null;
        try {
            URL iconUrl = new URL(url);
            URLConnection conn = iconUrl.openConnection();
            HttpURLConnection http = (HttpURLConnection) conn;

            int length = http.getContentLength();

            conn.connect();
            // 获得图像的字符流
            InputStream is = conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is, length);
            bm = BitmapFactory.decodeStream(bis);
            bis.close();
            is.close();// 关闭流
            Message message=Message.obtain();
            message.what=0;
            message.obj=bm;
            handler.sendMessage(message);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        bg=bm;
        return bm;
    }


    public Bitmap drawTextToBitmap(Context mContext, Bitmap bit, String mText, String str3) {

        try {
            Resources resources = mContext.getResources();
            float scale = resources.getDisplayMetrics().density;
// Bitmap bitmap = BitmapFactory.decodeResource(resources, resourceId);
            result1 = bit;
            Bitmap.Config bitmapConfig = result1.getConfig();
            if (bitmapConfig == null) {
                bitmapConfig = Bitmap.Config.ARGB_8888;
            }
            result1 = result1.copy(bitmapConfig, true);
            Canvas canvas = new Canvas(result1);
            Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);//消除锯齿
            paint.setDither(true);//获取跟清晰的图像采样
            paint.setFilterBitmap(true);//过滤一些
            paint.setColor(Color.RED);
            paint.setTextSize((int) (15 * scale));
            paint.setShadowLayer(1f, 0f, 1f, Color.DKGRAY);//阴影制作半径，x偏移量，y偏移量，阴影颜色
            Rect bounds = new Rect();
            paint.getTextBounds(mText, 0, mText.length(), bounds);
            int y = (result1.getHeight() + bounds.height()) / 4;
            int x = 0;
//Toast.makeText(MyCaremaActivity.this,"x"+bitmap.getHeight() +"y"+y +"y*sace"+ y * scale+"sace"+scale,Toast.LENGTH_LONG).show();
            Log.v("===位置", "x" + result1.getHeight() + "y" + y + "y*sace" + y * scale + "sace" + scale);
            canvas.drawText(mText, x * scale, y * scale, paint);
            canvas.drawText(str3, x * scale, y * scale + 25, paint);
// canvas.drawText(mText, x * scale, 210, paint);
// canvas.drawText(str3, x * scale,210 + 25 , paint);
            Log.v("===合成图片", "====ok" + mText);
            return result1;
        } catch (Exception e) {
//TODO: handle exception
            return null;
        }


    }

    private static Bitmap AddTimeWatermark(Bitmap mBitmap) {
        //获取原始图片与水印图片的宽与高
        int mBitmapWidth = mBitmap.getWidth();
        int mBitmapHeight = mBitmap.getHeight();
        Bitmap mNewBitmap = Bitmap.createBitmap(mBitmapWidth, mBitmapHeight, Bitmap.Config.ARGB_8888);
        Canvas mCanvas = new Canvas(mNewBitmap);
        //向位图中开始画入MBitmap原始图片
        mCanvas.drawBitmap(mBitmap,0,0,null);
        //添加文字
        Paint mPaint = new Paint();
        String mFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss EEEE").format(new Date());
        //String mFormat = TingUtils.getTime()+"\n"+" 纬度:"+GpsService.latitude+"  经度:"+GpsService.longitude;
        mPaint.setColor(Color.RED);
        mPaint.setTextSize(20);
        //水印的位置坐标
        mCanvas.drawText(mFormat, (mBitmapWidth * 1) / 10,(mBitmapHeight*14)/15,mPaint);
        mCanvas.save();
        mCanvas.restore();

        return mNewBitmap;
    }






}

